﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.InsuranceProducts;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceProducts;
using EnumHelper = ZBJF.Warranty.Common.Common.EnumHelper;

namespace ZBJF.Warranty.H5.Controllers
{
    public class InsuranceProductOrderController : BaseController
    {
        #region 分月详情
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 获取某一个月的订单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult GetInsuranceProductOrderByOneMonth(InsuranceProductOrderModel model)
        {
            model.SellerEmployeeID = CurrentUser.ID;
            int total;
            model.iSorts = "CreateOrderTime desc";
            var list = ServiceFactory.InsuranceProductOrderServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.InsuranceProductName,
                StatusDesc = EnumHelper.Instance.GetDescription(typeof(InsuranceProductOrderStatus), o.Status),
                CreateOrderTime = o.CreateOrderTime.ToString("MM月dd日 HH:mm"),
                TotalPirce = o.TotalPirce.ToString("C")
            });

            var dtMonth = model.MonthDateTime.HasValue
                ? model.MonthDateTime.Value.ToString("yyyyMM")
                : DateTime.Now.ToString("yyyyMM");
            var saleIncome = ServiceFactory.InsuranceProductOrderServiceInstance.GetSellerInsuranceProductSaleIncome(dtMonth,
                 CurrentUser.ID);
            var saleCount = ServiceFactory.InsuranceProductOrderServiceInstance.GetSellerInsuranceProductSaleCount(dtMonth,
                CurrentUser.ID, 0, InsuranceProductOrderStatus.Paid);
            return Json(new
            {
                saleIncome,
                saleCount,
                isLastPage = model.iDisplayStart + model.iDisplayLength > total,
                list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 已支付、已取消、已超时列表与详情页面（pdf下载）

        [LoginFilter(IsCheck = false)]
        public ActionResult Detail(int id)
        {
            var insuranceProductOrder = ServiceFactory.InsuranceProductOrderServiceInstance.LoadById(id);
            return View(insuranceProductOrder);
        }

        [LoginFilter(IsCheck = false)]
        public ActionResult PaySuccess(int id)
        {
            var insuranceProductOrder = ServiceFactory.InsuranceProductOrderServiceInstance.LoadById(id);
            return View(insuranceProductOrder);
        }
        [LoginFilter(IsCheck = false)]
        public ActionResult EmailTemplate(int id)
        {
            var insuranceProductOrder = ServiceFactory.InsuranceProductOrderServiceInstance.LoadById(id);
            return View(insuranceProductOrder);
        }


        [LoginFilter(IsCheck = false)]
        public ActionResult DownloadDetailAsPDF(int id)
        {
            var insuranceProductOrder = ServiceFactory.InsuranceProductOrderServiceInstance.LoadById(id);
            var bytes = new PechkinPDF().ConvertUrlToBytes("http://" + HttpContext.Request.Url.Authority + Url.Action("EmailTemplate", new { id = id }), 24);
            return File(bytes, "application/pdf", string.Format("{0}_{1}_{2}.pdf", insuranceProductOrder.InsuranceProductName, insuranceProductOrder.OrderNo, DateTime.Now.ToString("yyyyMMddHHmmss")));
        }
        #endregion

        #region 创建、取消订单与支付页面
        [LoginFilter(IsCheck = false)]
        [WeiXinLoginFilterAttribute(CheckLogin = true)]
        public ActionResult Pay(int id)
        {
            var insuranceProductOrder = ServiceFactory.InsuranceProductOrderServiceInstance.LoadById(id);
            return View(insuranceProductOrder);
        }
        /// <summary>
        /// 创建订单不需要登录，两个模型绑定
        /// </summary>
        /// <param name="model"></param>
        /// <param name="productOrder"></param>
        /// <returns></returns>
        [LoginFilter(IsCheck = false)]
        [WeiXinLoginFilterAttribute(CheckLogin = true)]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateOrder(SellerInsuranceProducts model, InsuranceProductOrder productOrder)
        {
            var sellerProduct = ServiceFactory.SellerInsuranceProductsServiceInstance.LoadById(model.ID);
            var insuranceProductList = ServiceFactory.InsuranceProductsServiceInstance.LoadAllInsuranceProductsBy(model.ID).ToList();
            var insuranceCompany = new InsuranceCompany();
            if (sellerProduct != null && sellerProduct.InsuranceCompanyID.HasValue)
            {
                insuranceCompany = ServiceFactory.InsuranceCompanyServiceInstance.Load(sellerProduct.InsuranceCompanyID.Value);
            }
            SellerEmployee sellerEmpoyee = CurrentUser ?? ServiceFactory.SellerEmployeeServiceInstance.LoadByID(productOrder.SellerEmployeeID);
            if (!insuranceProductList.Any() || sellerProduct == null)
            {
                TempData["success"] = false;
                TempData["Msg"] = string.Format("商家已下架该商品，请重新选择要购买的商品！");
                return RedirectToAction("Index", "Home");
            }
            var saleQty = ServiceFactory.InsuranceProductOrderCardServiceInstance.GetInsuranceCardCount(model.ID, 0);
            if (sellerProduct.MaxSalesQty - saleQty <= 0)
            {
                TempData["success"] = false;
                TempData["Msg"] = string.Format("该商品【{0}】已售完，请选择其他商品！", sellerProduct.ProductName);
                Debug.Assert(Request.UrlReferrer != null, "Request.UrlReferrer == null");
                return Redirect(Request.UrlReferrer.AbsoluteUri.ToString());
            }
            var hasBuyQty = ServiceFactory.InsuranceProductOrderServiceInstance.GetIdentityCardHasBuyQty(model.ID,
                productOrder.BuyUserIDNo);//获取改身份证用户已购买的产品数量
            if (hasBuyQty >= sellerProduct.IdentityCardLimitQty)//如果已经超过限制，则不允许购买
            {
                TempData["success"] = false;
                TempData["Msg"] = string.Format("该商品【{0}】已限制同一身份证用户最多只能购买{1}个，您已购买{2}个！", sellerProduct.ProductName, sellerProduct.IdentityCardLimitQty, hasBuyQty);
                Debug.Assert(Request.UrlReferrer != null, "Request.UrlReferrer == null");
                return Redirect(Request.UrlReferrer.AbsoluteUri.ToString());
            }
            var order = new InsuranceProductOrder()
            {
                OrderNo = CommonMethod.GetTimeStamp(),
                InsuranceProductName = sellerProduct.ProductName,
                SellerInsuranceProductID = sellerProduct.ID,
                InsuranceCompanyID = insuranceCompany.ID,
                InsuranceCompany = insuranceCompany.CompanyName ?? "",
                InsuranceCompanyBranch = insuranceCompany.ParentCompanyName ?? "",
                SellerEmployeeID = sellerEmpoyee.ID,
                SellerEmployeeName = sellerEmpoyee.UserName,
                SellerID = sellerEmpoyee.SellerId,
                SellersName = sellerEmpoyee.Sellers.SellersName,
                SaleRetailPrice = sellerProduct.SaleRetailPrice,
                CreateOrderTime = DateTime.Now,
                Status = (byte)InsuranceProductOrderStatus.PendingPayment,
                BuyCount = productOrder.BuyCount,
                TotalPirce = sellerProduct.SaleRetailPrice * productOrder.BuyCount,
                BuyUserName = productOrder.BuyUserName,
                BuyUserIDNo = productOrder.BuyUserIDNo,
                BuyUserPhone = productOrder.BuyUserPhone,
                BuyUserEmail = productOrder.BuyUserEmail,
                PayType = productOrder.PayType
            };
            var result = ServiceFactory.InsuranceProductOrderServiceInstance.AddEntities(order);
            if (result.ID > 0)
            {
                #region 不在此处创建订单快照
                ////1.信息收集配置
                //ServiceFactory.InsuranceProductInfoCollectItemSnapshootServiceInstance.CreateSnapshoot(result.ID, result.OrderNo, model.ID
                //    );
                ////3.商家产品信息
                //ServiceFactory.InsuranceProductSellerProductsSnapshootServiceInstance.CreateSnapshoot(result.ID,
                //    result.OrderNo, result.SellerInsuranceProductID);
                ////4.产品审核配置
                //ServiceFactory.InsuranceProductAuditProjectConfigurationSnapshootServiceInstance.CreateSnapshoot(result.ID,
                //   result.OrderNo, result.SellerInsuranceProductID);
                ////5.可用型号
                //ServiceFactory.InsuranceProductAvailableModelSnapshootServiceInstance.CreateSnapshoot(result.ID,
                //   result.OrderNo, result.SellerInsuranceProductID);
                ////6.可用屏幕配置
                //ServiceFactory.InsuranceProductAvailableScreenSnapshootServiceInstance.CreateSnapshoot(result.ID,
                //   result.OrderNo, result.SellerInsuranceProductID);
                ////7.可用屏幕
                //ServiceFactory.InsuranceProductScreenSPsSnapshootServiceInstance.CreateSnapshoot(result.ID,
                //   result.OrderNo, result.SellerInsuranceProductID);
                ////8.维修方式
                //ServiceFactory.InsuranceProductWarrantyMaintenanceTypesSnapshootServiceInstance.CreateSnapshoot(result.ID,
                //   result.OrderNo, result.SellerInsuranceProductID); 
                #endregion

                TempData["Msg"] = "请于15分钟内完成支付！";
                return RedirectToAction("Pay", new { id = result.ID });
            }
            else
            {
                TempData["Msg"] = "当前页面有问题，请重新购买！";
                return RedirectToAction("Index", "Home");
            }
            return RedirectToAction("Index", "Home");
        }
        [HttpPost]
        [ValidateInput(true)]
        [ValidateAntiForgeryToken]
        public ActionResult CancelOrder(int id)
        {
            var insuranceProductOrder = ServiceFactory.InsuranceProductOrderServiceInstance.LoadById(id);
            insuranceProductOrder.CancelTime = DateTime.Now;
            insuranceProductOrder.Status = (byte)InsuranceProductOrderStatus.UserCancel;
            var result = ServiceFactory.InsuranceProductOrderServiceInstance.UpdateEntities(insuranceProductOrder);
            TempData["success"] = result;
            TempData["msg"] = result ? "取消成功！" : "取消失败！";
            return RedirectToAction("Pay", new { id = id });
        }

        #endregion
    }
}